import { getChatStream, postChatQuery, postChatVllmQuery } from "@/api";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useState } from "react";
import { useSelector } from "react-redux";
import { RootStateI, UserI } from "@/types/system";
import { baseUrl } from "@/api/http_class";
import { ChatRequestI, MessageI } from "@/types/chat";

function HtmlRender({ html }: { html: string }) {
  return <div dangerouslySetInnerHTML={{ __html: html }} />;
}

const ChatInterfaceStream = () => {
  const content = `
  <div class="text-lg text-gray-800">参考资料搜索完成</div>
  我们知识库中找到<strong class="text-red-500">2</strong>种品规：
  <ol class="pl-5 list-decimal">
    <li class="mb-2">
      <a href="http://10.2.2.89/7257679834057277440/def" class="text-blue-500 underline">优思明(屈螺酮炔雌醇片)</a> &nbsp;&nbsp; 3mg:0.03mg x21片/盒 &nbsp;&nbsp;  德国Bayer Weimar GmbH & Co.KG(拜耳医药保健有限公司广州分公司分装)
    </li>
    <li class="mb-2">
      <a href="http://10.2.2.89/7257679834053083136/def" class="text-blue-500 underline">优思明(屈螺酮炔雌醇片)</a> &nbsp;&nbsp;  3mg: 0.3mg /片 &nbsp;&nbsp;  德国Bayer Weimar GmbH & Co.KG(拜耳医药保健有限公司广州分公司分装)
    </li>
  </ol>
  <div class="italic">优思明是一种口服避孕药，专门用于治疗乳腺癌。</div>
`;
  const [messages, setMessages] = useState<
    Array<{
      role: "user" | "assistant";
      content: string;
    }>
  >([
    { role: "user", content: "优思明是治疗什么病的？" },
    { role: "assistant", content: content },
  ]);
  const [streamMessages, setStreamMessages] = useState<string[]>([]);
  const [model, setModel] = useState("general");
  const [input, setInput] = useState("优思明是治疗什么病的？");
  // const [input, setInput] = useState("请以AI为主题写10000字的文章");
  const user: UserI = useSelector((state: RootStateI) => state.user);

  function uploadFiles() {
    const fileInput = document.getElementById(
      "fileInput"
    ) as HTMLInputElement | null;
    if (!fileInput || !fileInput.files) return;

    const formData = new FormData();

    for (let i = 0; i < fileInput.files.length; i++) {
      formData.append("files", fileInput.files[i]);
    }

    fetch("/api/upload", {
      method: "POST",
      body: formData,
    })
      .then((response) => response.json())
      .then((data) => {
        console.log("上传成功:", data);
      })
      .catch((error) => {
        console.error("上传失败:", error);
      });
  }

  const onChat = async () => {
    if (!input.trim()) return;
    // 深度拷贝messages
    let messagesCopy: MessageI[] = JSON.parse(JSON.stringify(messages));
    messagesCopy.push({
      role: "user",
      content: input,
      status: "pending",
      timestamp: Date.now(),
    });

    let data: ChatRequestI = {
      model: model,
      max_length: 10000,
      messages: messagesCopy,
    };

    const responseStream = await fetch(
      "http://localhost:8001/api/v1/chat_vllm/stream/",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(data),
      }
    );

    if (!responseStream.ok || !responseStream.body) {
      alert("Error fetching the response");
      return;
    }

    const reader = responseStream.body.getReader();
    const decoder = new TextDecoder("utf-8");
    let done = false;

    while (!done) {
      const { value, done: doneReading } = await reader.read();
      done = doneReading;
      const chunkValue = decoder.decode(value, { stream: true });

      console.log(chunkValue);

      // 手动解析 SSE 数据
      const lines = chunkValue
        .split("\n")
        .filter((line) => line.startsWith("data: "));
      for (const line of lines) {
        const data = JSON.parse(line.replace("data: ", ""));
        try {
          console.log(data);
          setStreamMessages((prev) => [...prev, data]);
          // 取出messagesCopy的最后一个元素
          // 如果lastMessage的role为assistant，则将event.data添加到lastMessage的content后面
          if (messagesCopy[messagesCopy.length - 1].role === "assistant") {
            messagesCopy[messagesCopy.length - 1].content += data;
          } else {
            messagesCopy.push({
              role: "assistant",
              content: data,
              status: "complete",
              timestamp: Date.now(),
            });
          }
          console.log(messagesCopy);
          // 设置messagesCopy
          setMessages(messagesCopy);
          setInput("");
        } catch (e) {
          console.error("Failed to parse SSE data:", e);
        }
      }
    }
  };

  return (
    <div className="flex h-screen flex-col">
      {/* 头部 */}
      <header className="border-b p-4">
        <h1 className="text-xl font-semibold">药学咨询</h1>
        {/* 下拉框选择模型 */}
        <select
          className="mt-2 ml-4"
          onChange={(e) => setModel(e.target.value)}
        >
          <option value="general">通用模型</option>
          <option value="medicine">药学模型</option>
        </select>
      </header>
      {/* 聊天区域 */}
      <ScrollArea className="flex-1 p-4">
        <div className="space-y-4">
          {messages.map((message, i) => (
            <div
              key={i}
              className={`flex ${
                message.role === "user" ? "justify-end" : "justify-start"
              }`}
            >
              <div
                className={`rounded-lg p-4 max-w-[80%] ${
                  message.role === "user"
                    ? "bg-primary text-primary-foreground"
                    : "bg-muted"
                }`}
              >
                <HtmlRender html={message.content} />
              </div>
            </div>
          ))}
        </div>
      </ScrollArea>
      {/* 输入区域 */}
      <div className="border-t p-4">
        <div className="flex gap-2">
          <Input
            value={input}
            onChange={(e) => setInput(e.target.value)}
            placeholder="输入您的问题..."
            className="flex-1"
          />
          {/* {streamMessages.join("")} */}
          <Button onClick={onChat}>发送</Button>
        </div>
      </div>
    </div>
  );
};

export default ChatInterfaceStream;
